const superagent = require('superagent');
const md5 = require('md5');
const cron = require('node-cron');

const { Warn, Record, Vehicle } = require('../db');

const { dateFormat } = require('../utils');
const CONFIG = require('../../config');
const { INDEX } = require('../../config');

const inner = () => {};

// 获取当前日期
inner.getAccessToken = () => {
  const { CONSTNTSTR } = CONFIG;
  const date = dateFormat(new Date(), 'Y-m-d').replace(/\-/g, '');
  const token = md5(`${CONSTNTSTR}${date}`);
  return token;
};

// 请求数据
inner.getData = async() => {
  const { HOST } = CONFIG;
  const token = inner.getAccessToken();
  const url = `${HOST}?index=${INDEX}&token=${token}`;
  const res = await superagent.post(url);
  if(res.text) {
    const data = JSON.parse(res.text);
    for(const key in data) {
      if(key.includes('Time')) {
        data[key] = inner.convertTime(data[key]);
      }
    }
    console.log(data);
    const params = data.data[0];
    await inner.getRecordInfo(params);
    await inner.getVehicleInfo(params);
    await inner.getWarnInfo(params);
    console.log('complete');
  }
};

// 准换时间信息为时间戳
inner.convertTime = (time) => {
  return new Date(time).getTime();
};

// 获取设备基本信息
inner.getVehicleInfo = async (data) => {
  const {
    vehId,
    vinCode,
    productName,
    locationStatus,
    accHours,
    speed,
    direction,
    altitude,
    lng,
    lat } = data;

  const vehcile = await Vehicle.findOne({ vehId, vinCode }).catch(err => console.log(err));
  if(vehcile) {
    await Vehicle.updateMany(
      { '_id': vehcile._id },
      {
        vehId,
        vinCode,
        productName,
        locationStatus,
        accHours,
        speed,
        direction,
        altitude,
        lng,
        lat,
      });
  } else {
    const vehcile = new Vehicle({
      vehId,
      vinCode,
      productName,
      locationStatus,
      accHours,
      speed,
      direction,
      altitude,
      lng,
      lat,
    });
    console.log(vehcile);
    vehcile.save();
  }
};

// 获取设备报警信息
inner.getWarnInfo = async (data) => {
  const { alarmList } = data;
  if(alarmList && typeof alarmList === 'object') {
    for(const alarm of alarmList) {
      const { vinCode, startTime, endTime, productName, lng, lat, alarmType, iconUrl, accStatus } = alarm;
      const warnInfo = new Warn({
        vinCode,
        startTime: new Date(startTime).getTime(),
        endTime: new Date(endTime).getTime(),
        productName,
        lng,
        lat,
        alarmType,
        iconUrl,
        accStatus,
      });

      warnInfo.save();
    }
  }
};

// 存储数据信息
inner.getRecordInfo = async(data) => {
  if(data) {
    const record = new Record(data);
    record.save();
  }
};

// 发起定时任务
const schedule = () => {
  cron.schedule('59 * * * * *', async() => {
    await inner.getData();
  });
};

module.exports = schedule;

